using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Result;

namespace FytSoa.CrossCutting.Middleware.Filter
{
    public class ExceptionFilter
    {
        private readonly RequestDelegate _next;

        public ExceptionFilter (RequestDelegate next) {
            _next = next;
        }

        public async Task Invoke (HttpContext context) {
            try {
                await _next (context);
            } catch (Exception ex) {
                await ExceptionHandlerAsync (context, ex);
            }
        }

        private async Task ExceptionHandlerAsync (HttpContext context, Exception ex) {
            context.Response.ContentType = "application/json";
            Logger.Error(ex);
            var result = new
            {
                code=500,
                message=ex.Message
            };
            await context.Response.WriteAsync (JsonConvert.SerializeObject(result));
        }
    }
}